const { User } = require('../models');
const { buildPaginationResponse } = require('../middleware/pagination');

// 列表（分页 + 状态/邮箱筛选）
const listUsers = async (req, res) => {
  try {
    const { status, email } = req.query;
    const query = {};

    if (status === 'enabled') query.isActive = true;
    if (status === 'disabled') query.isActive = false;
    if (email) query.email = { $regex: email.trim(), $options: 'i' };

    const total = await User.countDocuments(query);
    const users = await User.find(query)
      .sort({ createTime: -1 })
      .skip(req.pagination.skip)
      .limit(req.pagination.limit)
      .select('-password');

    const payload = buildPaginationResponse(users, total, req);
    res.json({ success: true, ...payload });
  } catch (error) {
    res.status(500).json({ success: false, message: '获取用户列表失败', error: error.message });
  }
};

// 创建用户
const createUser = async (req, res) => {
  try {
    const { username, email, password, role, isActive } = req.body;

    // 唯一性检查
    const exists = await User.findOne({ $or: [{ email }, { username }] });
    if (exists) {
      return res.status(400).json({ success: false, message: '用户名或邮箱已存在' });
    }

    const user = new User({ username, email, password, role, isActive });
    await user.save();
    res.status(201).json({ success: true, message: '用户创建成功', data: user });
  } catch (error) {
    res.status(500).json({ success: false, message: '创建用户失败', error: error.message });
  }
};

// 更新用户（不含密码）
const updateUser = async (req, res) => {
  try {
    const { id } = req.params;
    const { username, email, role, isActive } = req.body;

    // 唯一性校验（排除当前）
    if (email) {
      const byEmail = await User.findOne({ email, _id: { $ne: id } });
      if (byEmail) return res.status(400).json({ success: false, message: '邮箱已存在' });
    }
    if (username) {
      const byName = await User.findOne({ username, _id: { $ne: id } });
      if (byName) return res.status(400).json({ success: false, message: '用户名已存在' });
    }

    const updated = await User.findByIdAndUpdate(
      id,
      { username, email, role, isActive },
      { new: true, runValidators: true }
    ).select('-password');

    if (!updated) return res.status(404).json({ success: false, message: '用户未找到' });
    res.json({ success: true, message: '用户更新成功', data: updated });
  } catch (error) {
    res.status(500).json({ success: false, message: '更新用户失败', error: error.message });
  }
};

// 更新状态
const updateStatus = async (req, res) => {
  try {
    const { id } = req.params;
    const { isActive } = req.body;
    const updated = await User.findByIdAndUpdate(
      id,
      { isActive: Boolean(isActive) },
      { new: true }
    ).select('-password');
    if (!updated) return res.status(404).json({ success: false, message: '用户未找到' });
    res.json({ success: true, message: '状态更新成功', data: updated });
  } catch (error) {
    res.status(500).json({ success: false, message: '更新状态失败', error: error.message });
  }
};

// 重置密码
const resetPassword = async (req, res) => {
  try {
    const { id } = req.params;
    const { newPassword } = req.body;
    const user = await User.findById(id);
    if (!user) return res.status(404).json({ success: false, message: '用户未找到' });
    user.password = newPassword;
    await user.save();
    res.json({ success: true, message: '密码重置成功' });
  } catch (error) {
    res.status(500).json({ success: false, message: '密码重置失败', error: error.message });
  }
};

// 删除
const deleteUser = async (req, res) => {
  try {
    const { id } = req.params;
    const user = await User.findById(id);
    if (!user) return res.status(404).json({ success: false, message: '用户未找到' });
    await User.findByIdAndDelete(id);
    res.json({ success: true, message: '用户已删除' });
  } catch (error) {
    res.status(500).json({ success: false, message: '删除用户失败', error: error.message });
  }
};

module.exports = {
  listUsers,
  createUser,
  updateUser,
  updateStatus,
  resetPassword,
  deleteUser
};


